package xyc.szk.web.servlet.context;
/*
 * @Description:
 * @Author: 山志凯
 * @Date: 2021-03-17
 * @Time: 09:19
 */

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@WebServlet(value = "/context02",initParams = {@WebInitParam(name = "app",value = "windows"),
        @WebInitParam(name = "version",value = "10.0")})

public class ContextServlet02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        // this.getServletConfig().getServletContext(); //这样也可以获取ServletContext对象
        System.out.println("context02:" + context);
        //注意：ServletContext对象是一个域对象，即它是由使用范围的对象，它的使用范围是整个web应用，
        //也就是它存储的信息可以在任何一个servlet中使用，它是针对所有用户的所有请求
        //context.setAttribute("className","19软工2班");

        //读web下的配置文件jdbc.properties
        Properties properties = new Properties();
        //1、根目录下的（jdbc03）
        //context.getResourceAsStream()的参数路径只能是相对路径，不能使绝对路径
        InputStream in03 = context.getResourceAsStream("/jdbc.properties");
        System.out.println(in03);
        properties.load(in03);
        //lambda表达式，箭头函数
        properties.forEach((k,v)->System.out.println(k+":"+v));

        //2、对根目录下web-inf下的jdbc.properties
        InputStream in02 = context.getResourceAsStream("/WEB-INF/jdbc.properties");
        System.out.println(in02);
        properties.load(in02);
        //lambda表达式，箭头函数
        properties.forEach((k,v)->System.out.println(k+":"+v));

        //3、src目录下的jdbc.properties
        InputStream in01 = context.getResourceAsStream("/WEB-INF/classes/jdbc.properties");
        System.out.println(in01);
        properties.load(in01);
        //lambda表达式，箭头函数
        properties.forEach((k,v)->System.out.println(k+":"+v));
    }
}
